package haois.module.system.rest;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import haois.constant.Reply;
import haois.constant.ReturnState;
import haois.constant.daomain.SmsRep;
import haois.module.system.service.AliCloudService;
import haois.module.system.service.SmsRecordService;
import haois.util.DateUtil;
import haois.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


/**
 * Created by RuiHaoZ on 2018/4/9 21:40
 */
@RestController
@RequestMapping("/api/sys/ali")
public class AliCloudController {

    @Autowired
    private AliCloudService aliCloudService;
    @Autowired
    private SmsRecordService smsRecordService;

    /**
     * @api {POST} /api/sys/ali/sendCode 发送验证码
     * @apiGroup sysAliCloud
     * @apiName sendCode
     * @apiDescription 发送验证码，号码仅仅 每月一次
     * @apiParam {String} phoneNumbers 电话号码
     * @apiParamExample {json} 请求样例：
     * POST /api/sys/ali/sendCode
     * @apiSuccessExample {json} 返回样例:
     * {"code":"00","msg":"成功"}
     */
    @RequestMapping(value = "/sendCode", method = RequestMethod.POST, params = {"phoneNumbers"})
    public String sendCode(String phoneNumbers) {
        try {
            if (!StrUtil.isPhone(phoneNumbers)) {
                return new Reply(ReturnState.CODE_10,"手机号码格式不正确").toJson();
            }
            String code = StrUtil.getRandom(5);
            SmsRep oldSmsRep = smsRecordService.getByMobile(phoneNumbers);
            if (oldSmsRep != null && DateUtil.isThisMonth(oldSmsRep.getCreateTime().getTime())) {
                return new Reply(ReturnState.CODE_06,
                        "每个自然月只允许发送一次验证码", oldSmsRep.getPhoneCode()).toJson();
            }
            SendSmsResponse sendSms = aliCloudService.sendCode(phoneNumbers, code);
            SmsRep smsRep = new SmsRep(sendSms, phoneNumbers, code);
            smsRecordService.add(smsRep);
            return new Reply<SendSmsResponse>(ReturnState.CODE_00,
                    "发送短信成功", smsRep).toJson();

        } catch (Exception e) {
            return new Reply(ReturnState.CODE_10, e.getMessage()).toJson();
        }

    }
}
